﻿// ===============================================================================
// XCI.Parent 西安交通信息WinForm开发框架 2019 版权所有
// ===============================================================================

using System;
using DevExpress.XtraTreeList.Nodes;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Extensions;
using XCI.Windows;
using XCI.Windows.Extensions;
using XCI.Windows.Helper;

namespace XCI.Sys.Forms
{
    /// <summary>
    /// 系统部门管理
    /// </summary>
    [FormCaption("系统部门管理")]
    public partial class FrmDeptManager : FrmSysBase
    {
        /// <summary>
        /// 树控件操作类
        /// </summary>
        private TreeHelper<SysDept> helper;
        private readonly bool allowSelect = SysRuntime.IsAuthorize("sys.dept.select");
        private readonly bool allowInsert = SysRuntime.IsAuthorize("sys.dept.insert");
        private readonly bool allowUpdate = SysRuntime.IsAuthorize("sys.dept.update");
        private readonly bool allowDelete = SysRuntime.IsAuthorize("sys.dept.delete");
        private readonly bool allowExport = SysRuntime.IsAuthorize("sys.dept.export");

        public FrmDeptManager()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 页面初始化
        /// </summary>
        private void InitForm()
        {
            //1.初始化表格操作类
            helper = new TreeHelper<SysDept>(tree);
            helper.ElapsedTimeItem = labExecuteTime;
            helper.AutoCheckedChildNode = true;
            helper.IsReserveNodeExpandedStatus = true;
            helper.IsReserveNodeFocused = true;
            helper.ModifyData += Helper_ModifyData;
            helper.NodeChecked += Helper_NodeChecked;

            //2.加载数据
            LoadData();

            //设置第一个节点为焦点
            helper.FocusFirstNode();
            ButtonStatus();
        }

        private void Helper_NodeChecked(object sender, EventArgs e)
        {
            ButtonStatus();
        }

        /// <summary>
        /// 更新节点顺序和父节点
        /// </summary>
        private void Helper_ModifyData(object sender, EventArgs e)
        {
            var list = helper.GetChangedDataList();
            helper.ClearDataChanged();
            DeptService.Instance.BatchUpdateValues(list);
        }

        /// <summary>
        /// 数据加载
        /// </summary>
        private void LoadData()
        {
            //权限控制
            if (!allowSelect) return;

            var status = statusCombo.SelectedValue.ToStringOrEmpty();
            helper.RunCallback(e =>
            {
                e.Result = DeptService.Instance.SelectList(status);
            })
            .CompletCallback(e =>
            {
                tree.Filter();
                OnceAction("expandAllNode", () =>
                {
                    //展开全部节点
                    helper.ExpandAll();
                });
                ButtonStatus();
            })
            .RunAsync();
        }

        /// <summary>
        /// 数据编辑
        /// </summary>
        /// <param name="created">是否新建</param>
        /// <param name="parentNode">父节点对象</param>
        /// <param name="model">模型对象</param>
        private void Edit(bool created, TreeListNode parentNode, SysDept model)
        {
            var editForm = new FrmDeptEdit();
            editForm.SetModel(created, model, helper.Get(parentNode));
            editForm.ShowDialogOk(LoadData);
        }

        /// <summary>
        /// 获取选中的对象
        /// </summary>
        /// <returns>返回选中的对象</returns>
        private SysDept GetSelected()
        {
            return DeptService.Instance.SelectById(helper.SelectedId);
        }

        /// <summary>
        /// 设置按钮可用状态
        /// </summary>
        private void ButtonStatus()
        {
            var isSingle = !helper.HasMultiSelected && !helper.HasMultiChecked && helper.HasSelected;
            btnNew.Enabled = allowInsert;
            btnEdit.Enabled = isSingle && allowUpdate;
            btnCopy.Enabled = isSingle && allowInsert;
            btnDelete.Enabled = helper.HasChecked && allowDelete;
            btnExport.Enabled = helper.HasData && allowExport;
            btnRefresh.Enabled = allowSelect;
            btnRefreshCache.Enabled = allowSelect;
        }

        /// <summary>
        /// 页面加载事件
        /// </summary>
        private void FrmDeptManager_Load(object sender, EventArgs e)
        {
            InitForm();
        }

        private void tree_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            ButtonStatus();
        }

        private void tree_DoubleClick(object sender, EventArgs e)
        {
            helper.DblClickRow(e, () =>
            {
                var detailsForm = new FrmDeptDetails(helper.SelectedId);
                detailsForm.ShowDialogOk();
            });
        }

        private void statusCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            EndInit(LoadData);
        }

        private void btnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Edit(true, tree.FocusedNode, DeptService.Instance.New());
        }

        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Edit(false, tree.FocusedNode.ParentNode, GetSelected());
        }

        private void btnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Edit(true, tree.FocusedNode.ParentNode, DeptService.Instance.Copy(GetSelected()));
        }

        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            helper.DeleteByChecked(() =>
            {
                DeptService.Instance.Delete(helper.CheckedIds).IfTrue(() => { LoadData(); });
            });
        }

        private void btnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var status = statusCombo.SelectedValue.ToStringOrEmpty();
            ExcelExportCore(() => DeptService.Instance.Export(status), "系统部门");
        }

        private void BtnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            LoadData();
        }

        private void BtnRefreshCache_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DeptService.Instance.RefreshCache().IfTrue(() =>
            {
                LoadData();
                MessageBoxHelper.ShowMessage("服务器部门缓存刷新成功");
            });
        }
    }
}